package com.study.talk.data.repository

import android.util.Log
import com.study.common.annotation.Desc
import com.study.talk.data.remote.FileApi
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File
import javax.inject.Inject

class FileRepository @Inject constructor(private val fileApi: FileApi) : BaseRepository() {

    companion object {
        private const val TAG = "FileRepository"
    }

    suspend fun upload(path: String): String {
        return upload(File(path))
    }

    @Desc("上传单个文件")
    suspend fun upload(file: File): String {
        val response = fileApi.upload(
            MultipartBody.Part.createFormData(
                "mFile", file.name, file.asRequestBody("image/*".toMediaTypeOrNull())
            )
        )
        if (response.isSuccessful) {
            if (response.body()?.status == 200) {
                if (response.body()?.data != null) {
                    return response.body()?.data ?: ""
                } else {
                    Log.e(TAG, "upload: fail,response.body()?.data is null")
                    return ""
                }
            } else {

                Log.e(TAG, "upload: fail,msg : ${response.body()?.message}")
                return ""
            }
        } else {
            Log.e(TAG, "upload: fail,msg : ${response.message()}")
            return ""
        }
    }

    @Desc("上传多个文件")
    suspend fun uploads(paths: List<String>): List<String> {
        val response = fileApi.uploads(paths.map {
            MultipartBody.Part.createFormData(
                "files[]", File(it).name, File(it).asRequestBody("image/*".toMediaTypeOrNull())
            )
        })
        if (response.isSuccessful) {
            if (response.body()?.data != null) {
                return response.body()?.data ?: listOf()
            } else {
                Log.e(TAG, "uploads: fail,response.body()?.data is null")
                return listOf()
            }
        } else {
            Log.e(TAG, "upload: fail,msg : ${response.message()}")
            return listOf()
        }
    }
}